package com.hotelvip.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotelvip.common.utils.JSONResult;
import com.hotelvip.common.utils.JwtUtil;
import com.hotelvip.common.utils.RedisUtils;
import com.hotelvip.dao.SysUserMapper;
import com.hotelvip.entity.SysUser;
import com.hotelvip.vo.SysUserMenu;
import com.hotelvip.service.SysMenuService;
import com.hotelvip.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lzh
 * @date 2020/12/8 13:41
 */
@RestController
@RequestMapping(("/sys"))
@Api(basePath = "/sys",tags = "用户登录模块")
public class LoginController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysMenuService sysMenuService;


    /**
     * 新增用户
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "新增用户",httpMethod = "POST")
    @PostMapping("/register/{roleIds}")
    public JSONResult register(@RequestBody SysUser sysUser){
        Long[] roleIds = sysUser.getRoleIds();
        sysUserService.addUser(sysUser,roleIds);
        return JSONResult.ok();
    }
    @ApiOperation(value = "登录授权",httpMethod = "POST")
    @PostMapping("/doLogin")
    public JSONResult doLogin(@RequestBody SysUser sysUser ,HttpServletResponse response){
        RedisUtils redisUtils = new RedisUtils();
        String username = sysUser.getUsername();
        String password = sysUser.getPassword();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return JSONResult.errorMsg("用户名密码不能为空");
        }
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("username",username);
        SysUser dateSysUser = sysUserMapper.selectOne(sysUserQueryWrapper);
        //验证用户名
        if (dateSysUser==null) {
            throw new UnknownAccountException();
        }
        //校验密码
        password = new SimpleHash("MD5", password, dateSysUser.getSalt(), 1).toHex();
        if (!password.equals(dateSysUser.getPassword())){
            throw new IncorrectCredentialsException();
        }
        //密码正确

        long timeMillis = System.currentTimeMillis();
        String token = JwtUtil.sign((long)dateSysUser.getId(), timeMillis);
        dateSysUser.setPassword(null);
        //token放入redis
        redisUtils.setex("SYS_USER::["+dateSysUser.getId()+"]",(int) JwtUtil.REFRESH_EXPIRE_TIME, Long.toString(timeMillis));
        System.out.println(redisUtils.get(Long.toString(dateSysUser.getId())));
        response.setHeader("Authorization", token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        List<SysUserMenu> userMenus = sysMenuService.findUserMenusByUserId(dateSysUser.getId());

//        return new Result<>(CommonEnum.SUCCESS, dbUser);
        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("token", token);
        userInfo.put("sysUser", dateSysUser);
        userInfo.put("userMenus", userMenus);
//        SecurityUtils.getSubject().login(new JWTToken(token));
//        sysUserService.doLogin(username);
        return JSONResult.ok(userInfo,"登录成功");
    }
    @ApiOperation(value = "注销",httpMethod = "GET")
    @GetMapping("/doLogout")
    public JSONResult doLogout(HttpServletRequest request){
        /*
         * 清除redis中的RefreshToken即可
         */
        RedisUtils redisUtils = new RedisUtils();
        Long userId = JwtUtil.getUserId(request);
        redisUtils.del("SYS_USER::["+userId+"]");
        return JSONResult.ok("注销成功");
    }
//    @ApiOperation(value = "登录失败",httpMethod = "GET")
//    @GetMapping("/toLogin")
//    public JSONResult toLogin(){
//        return JSONResult.errorMsg("重新登录");
//    }
}
